/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-23 22:48:41
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-05-31 15:08:43
 * @FilePath: \vue3_nuxt_demo\server\api\note\index.get.ts
 * @Description: 获取用户文集下全部的文章
 */
import Joi from 'joi';
import { responseJson, getLoginUid, trimMarkdown, headCover } from '@/server/utils/helper';
import { getDB } from '@/server/utils/db';

/**
 * 1、判断用户是否登录
 * 2、已登录则获取全部的文章
 */

export default defineEventHandler(
  async (event)=>{

    //获取用户id，判断是否登录
    const uid = getLoginUid(event);

    // 判断用户id
    if (uid === 0) {
      setResponseStatus(event, 401);
      return responseJson(401,{
        success: false,
        msg: '请先登录'
      });
    }

    //获取数据
    const query = await getQuery(event);

    // 数据库交互
    const { find, close } = getDB();

    // 查询
    const con = find();

    try {

      const {pageNo = 1, pageSize = 100} = query as any;

      // 限制条数
      const limit = pageSize;

      // 开始位置
      const offset = (pageNo - 1) * pageSize;
      //获取用户文章
      const [notes] = await con.query(
        'SELECT notes.id AS id, notes.title, notes.content_md, notes.uid, users.nickname FROM `notes` LEFT JOIN `users` ON notes.uid = users.id WHERE `state`=? LIMIT ? OFFSET ?',
        [2, limit, offset]
      );

      const result = notes.map((item: any) => {
        return {
          ...item,
          subTitle: trimMarkdown(item.content_md,300),
          cover: headCover(item.content_md),
          like: 45,
          content_md: '',
          flag: false
        };
      });

      return  responseJson(200,{
        success: true,
        msg: '获取成功',
        data: result
      });
    }
    catch (error){
      setResponseStatus(event,500);
      return responseJson(500,{
        success: false,
        msg: '服务器错误',
        error: error
      });
    }
    finally {
      // 释放连接
      close();
    }
})